<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>结果分析 - 后台管理</title>
  <link rel="stylesheet" href="/static/base.css">
  <link rel="stylesheet" href="/static/components.css">
  <link rel="stylesheet" href="/static/pages.css">
  <link rel="stylesheet" href="/static/admin/admin.css">
</head>
<body>
  <div class="admin-layout">
    <!-- 顶部导航 -->
    <div class="admin-header">
      <h2>结果分析</h2>
      <div>
        <button class="btn" onclick="location.href='/'">返回前台</button>
        <button class="btn" onclick="logout()">退出</button>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="admin-main">
      <!-- 左侧导航（公共组件注入） -->
      <div class="admin-sidebar"></div>

      <!-- 右侧内容区域 -->
      <div class="admin-content">
        <div class="content-page active">
          <h3>结果分析</h3>
          <p class="page-description">分析策略执行结果的统计信息和分布情况</p>

          <div class="content-card">
            <div style="display:flex; gap:12px; flex-wrap:wrap; align-items:center;">
              <input id="param-date" type="date" class="form-control" style="width:200px;">
              <input id="param-strategy" type="text" class="form-control" placeholder="策略名（可选）" style="width:240px;">
              <button class="btn" onclick="reloadAnalysis()">分析</button>
              <button class="btn" onclick="resetParams()">清除</button>
            </div>
          </div>

          <div class="content-card">
            <h4>概览</h4>
            <div id="overview" class="stats-grid">
              <div class="stat-item">
                <span class="stat-label">股票数</span>
                <span id="sum-count" class="stat-value">-</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">平均涨跌幅</span>
                <span id="avg-change" class="stat-value">-</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">正收益数</span>
                <span id="pos-count" class="stat-value">-</span>
              </div>
            </div>
          </div>

          <div class="content-card">
            <h4>行业分布</h4>
            <div id="industry-chart" style="height:320px;"></div>
          </div>

          <div class="content-card">
            <h4>涨跌幅分布</h4>
            <div id="change-chart" style="height:320px;"></div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script src="/static/admin/components/sidebar.js"></script>
  <script>
    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
      // 设置默认日期为今天
      const dateInput = document.getElementById('param-date');
      if (dateInput) {
        dateInput.value = new Date().toISOString().split('T')[0];
      }
      
      // 从URL参数中获取初始值
      const urlParams = new URLSearchParams(window.location.search);
      if (urlParams.has('execution_date')) {
        dateInput.value = urlParams.get('execution_date');
      }
      if (urlParams.has('strategy')) {
        document.getElementById('param-strategy').value = urlParams.get('strategy');
      }
      
      reloadAnalysis();
      injectAdminSidebar('/admin/result-analysis');
    });

    // 结果分析相关函数
    async function reloadAnalysis(){
      try{
        const d = document.getElementById('param-date').value || new Date().toISOString().split('T')[0];
        const s = document.getElementById('param-strategy').value.trim();
        const params = new URLSearchParams();
        if(d) params.set('execution_date', d);
        if(s) params.set('strategy', s);
        const resp = await fetch('/admin/api/strategy/analysis?' + params.toString());
        const data = await resp.json();
        if(data && data.success){
          const rows = data.results || [];
          // 概览
          document.getElementById('sum-count').textContent = rows.length;
          const avg = rows.length ? (rows.reduce((acc, r) => acc + (Number(r.change_percent)||0), 0) / rows.length) : 0;
          document.getElementById('avg-change').textContent = avg.toFixed(2) + '%';
          document.getElementById('pos-count').textContent = rows.filter(r => (Number(r.change_percent)||0) > 0).length;

          drawIndustryChart(rows);
          drawChangeChart(rows);
        }
      }catch(e){
        console.error('加载分析失败', e);
      }
    }

    function resetParams(){
      document.getElementById('param-date').value = '';
      document.getElementById('param-strategy').value = '';
      reloadAnalysis();
    }

    function drawIndustryChart(rows){
      const dom = document.getElementById('industry-chart');
      if(!dom) return;
      
      const map = new Map();
      rows.forEach(r => {
        const k = r.industry || '未知';
        map.set(k, (map.get(k) || 0) + 1);
      });
      
      const data = Array.from(map.entries()).map(([name, value]) => ({name, value}));
      
      // 生成行业分布饼状图HTML
      if (data.length === 0) {
        dom.innerHTML = `<div style="padding:20px; text-align:center; color:#6c757d;">暂无行业分布数据</div>`;
        return;
      }
      
      // 按数量排序，取前8个，其他归为"其他"
      data.sort((a, b) => b.value - a.value);
      const topData = data.slice(0, 8);
      const otherCount = data.slice(8).reduce((sum, item) => sum + item.value, 0);
      
      if (otherCount > 0) {
        topData.push({name: '其他', value: otherCount});
      }
      
      let chartHtml = '<div style="padding:20px; display:flex; align-items:center; justify-content:space-between;">';
      
      // 饼状图
      chartHtml += '<div style="flex:1; text-align:center;">';
      chartHtml += '<h5 style="margin-bottom:15px; color:#2c3e50;">行业分布饼状图</h5>';
      
      const colors = ['#007bff', '#28a745', '#ffc107', '#dc3545', '#6f42c1', '#fd7e14', '#20c997', '#e83e8c', '#6c757d'];
      let currentAngle = 0;
      
      chartHtml += '<svg width="200" height="200" viewBox="0 0 200 200" style="margin:0 auto;">';
      
      topData.forEach((item, index) => {
        const percentage = (item.value / rows.length) * 100;
        const angle = (percentage / 100) * 360;
        const color = colors[index % colors.length];
        
        if (angle > 0) {
          const x1 = 100 + 80 * Math.cos(currentAngle * Math.PI / 180);
          const y1 = 100 + 80 * Math.sin(currentAngle * Math.PI / 180);
          const x2 = 100 + 80 * Math.cos((currentAngle + angle) * Math.PI / 180);
          const y2 = 100 + 80 * Math.sin((currentAngle + angle) * Math.PI / 180);
          
          const largeArcFlag = angle > 180 ? 1 : 0;
          
          chartHtml += `<path d="M 100 100 L ${x1} ${y1} A 80 80 0 ${largeArcFlag} 1 ${x2} ${y2} Z" fill="${color}" stroke="#fff" stroke-width="2"/>`;
          
          currentAngle += angle;
        }
      });
      
      chartHtml += '</svg>';
      chartHtml += '</div>';
      
      // 图例（可点击进行筛选）
      chartHtml += '<div style="flex:1; margin-left:20px;">';
      chartHtml += '<h5 style="margin-bottom:15px; color:#2c3e50;">图例（点击筛选）</h5>';
      
      topData.forEach((item, index) => {
        const percentage = ((item.value / rows.length) * 100).toFixed(1);
        const color = colors[index % colors.length];
        chartHtml += `
          <div style="display:flex; align-items:center; margin-bottom:8px; cursor:pointer;" onclick="filterByIndustry('${item.name}')" title="点击筛选行业：${item.name}">
            <div style="width:12px; height:12px; background:${color}; border-radius:2px; margin-right:8px;"></div>
            <span style="font-size:13px; color:#495057;">${item.name}</span>
            <span style="font-size:12px; color:#6c757d; margin-left:auto;">${item.value} (${percentage}%)</span>
          </div>
        `;
      });
      
      chartHtml += '</div>';
      chartHtml += '</div>';
      dom.innerHTML = chartHtml;
    }

    function drawChangeChart(rows){
      const dom = document.getElementById('change-chart');
      if(!dom) return;
      
      const ranges = [
        {name: '>10%', count: 0, color: '#28a745'},
        {name: '5%-10%', count: 0, color: '#4cd964'},
        {name: '0%-5%', count: 0, color: '#ff9500'},
        {name: '<0%', count: 0, color: '#ff3b30'}
      ];
      
      rows.forEach(r => {
        const change = Number(r.change_percent) || 0;
        if(change > 10) ranges[0].count++;
        else if(change > 5) ranges[1].count++;
        else if(change > 0) ranges[2].count++;
        else ranges[3].count++;
      });
      
      // 生成涨跌幅分布竖排图表HTML
      if (rows.length === 0) {
        dom.innerHTML = `<div style="padding:20px; text-align:center; color:#6c757d;">暂无涨跌幅分布数据</div>`;
        return;
      }
      
      let chartHtml = '<div style="padding:20px;">';
      chartHtml += '<h5 style="margin-bottom:15px; color:#2c3e50;">涨跌幅分布 (竖排柱状图)</h5>';
      
      const maxCount = Math.max(...ranges.map(r => r.count));
      const chartHeight = 200;
      
      chartHtml += '<div style="display:flex; align-items:end; justify-content:space-around; height:' + chartHeight + 'px; padding:20px 0;">';
      
      ranges.forEach(range => {
        const percentage = ((range.count / rows.length) * 100).toFixed(1);
        const barHeight = maxCount > 0 ? (range.count / maxCount * (chartHeight - 60)).toFixed(1) : 0;
        
        chartHtml += `
          <div style="display:flex; flex-direction:column; align-items:center; height:100%; cursor:pointer;" onclick="filterByChangeRange('${range.name}')" title="点击筛选：${range.name}">
            <div style="
              background:${range.color}; 
              width:40px; 
              height:${barHeight}px; 
              border-radius:4px 4px 0 0; 
              transition:height 0.3s ease;
              box-shadow:0 2px 4px rgba(0,0,0,0.1);
            "></div>
            <div style="margin-top:8px; text-align:center;">
              <div style="font-size:12px; color:#495057; font-weight:600;">${range.count}</div>
              <div style="font-size:11px; color:#6c757d;">${range.name}</div>
              <div style="font-size:10px; color:#6c757d;">${percentage}%</div>
            </div>
          </div>
        `;
      });
      
      chartHtml += '</div>';
      chartHtml += '</div>';
      dom.innerHTML = chartHtml;
    }
    // 点击图例跳转到前台基本面并带过滤参数
    function filterByIndustry(ind){
      if(!ind) return;
      const p = new URLSearchParams();
      p.set('industry', ind);
      p.set('only_today_labels', '1');
      window.location.href = '/fundamental?' + p.toString();
    }
    function filterByChangeRange(name){
      let min = '', max = '';
      switch(name){
        case '>10%': min = '10.01'; break;
        case '5%-10%': min = '5'; max = '10'; break;
        case '0%-5%': min = '0.01'; max = '5'; break;
        case '<0%': max = '0'; break;
        default: break;
      }
      const p = new URLSearchParams();
      if (min!=='') p.set('chg_min', min);
      if (max!=='') p.set('chg_max', max);
      p.set('only_today_labels', '1');
      window.location.href = '/fundamental?' + p.toString();
    }
  </script>

  <style>
    /* 结果分析页面专用样式 */
    
    /* 统计网格样式 */
    .stats-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 16px;
      margin-bottom: 24px;
    }

    .stat-item {
      background: linear-gradient(135deg, #ffffff, #f8f9fa);
      color: #2c3e50;
      padding: 20px;
      border-radius: 12px;
      text-align: center;
      box-shadow: 0 4px 12px rgba(0,0,0,0.08);
      transition: transform 0.3s ease;
      border: 1px solid #e9ecef;
    }

    .stat-item:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(0,0,0,0.12);
    }

    .stat-label {
      display: block;
      font-size: 14px;
      color: #6c757d;
      margin-bottom: 8px;
      font-weight: 500;
    }

    .stat-value {
      display: block;
      font-size: 28px;
      font-weight: 700;
      color: #2c3e50;
    }

    /* 图表容器样式 */
    #industry-chart,
    #change-chart {
      background: #f8f9fa;
      border: 1px solid #e9ecef;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
      .stats-grid {
        grid-template-columns: 1fr;
      }
      
      #industry-chart,
      #change-chart {
                 height: 200px !important;
       }
     }
   </style>

   <script>
     // 退出登录
     async function logout(){
       try{ 
         await fetch('/admin/logout', {method:'POST'}); 
         location.href='/admin/login'; 
       }catch(e){ 
         location.href='/admin/login'; 
       }
     }
   </script>
 </body>
 </html>
